﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Service.Infrastructure.Implement;
using Service.Infrastructure.Interface;
using FilterAttribute = System.Web.Http.Filters.FilterAttribute;

namespace Web.Filter
{
    /// <summary>
    ///     基类过滤器可在Controller注释
    /// 调用顺序：IAuthorizationFilter>IActionFilter>IResultFilter>IExceptionFilter
    /// </summary>
    public class BaseFilter : FilterAttribute
    {
        protected HttpRequestBase Request;
        protected ActionExecutingContext FilterContext;
        protected ControllerDescriptor ControllerDescriptor;

        protected void Init(ActionExecutingContext filterContext)
        {
            FilterContext = filterContext;
            Request = FilterContext.HttpContext.Request;
            ControllerDescriptor = FilterContext.ActionDescriptor.ControllerDescriptor;
        }

        protected readonly ILog ExcptionLogger = new ExceptionLogConfigService();
        protected readonly ILog UserVisitLogger = new UserLogService();


        protected void LoggingVist()
        {
            if (!FilterContext.IsChildAction)
            {

                UserVisitLogger.Logging(new Dictionary<String, String>{
                    {"Ip",GetIp(Request)},
                    {"Browser",GetBrowserVersion(Request)},
                    {"VisitPath",GetVisitUrl(Request)},
                    {"PostParams",GetPostParams(Request)},
                    {"IsAjax",GetIsAjax(Request)},
                    {"HttpMethod",GetHttpMethod(Request)},
                    {"Platform",GetPlatform(Request)}
                },
                String.Format("PreferredRendering:{0} >>> UserAgent:{1} >>> ", GetPreferredRendering(Request), GetUserAgent(Request)));

            }
        }

        /// <summary>
        ///     获取ip
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected String GetIp(HttpRequestBase request)
        {
            String ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(ip))
            {
                ip = request.ServerVariables["REMOTE_ADDR"];
            }

            return ip;
        }

        /// <summary>
        ///     浏览器版本
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected String GetBrowserVersion(HttpRequestBase request)
        {
            HttpBrowserCapabilitiesBase brObject = request.Browser;
            return String.Format("{0}-{1}", brObject.Type, brObject.Version);
        }

        /// <summary>
        ///     格式化并整合POST参数字符串
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected String GetPostParams(HttpRequestBase request)
        {

            const string str = "{0}:{1}&";
            return request.Form.Keys.Cast<string>().Aggregate(str, (current, key) => String.Format(current, key, request.Form[key]) + str);
        }

        /// <summary>
        ///     是否为Ajax请求
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected String GetIsAjax(HttpRequestBase request)
        {
            return String.Format("{0}", request.IsAjaxRequest());
        }

        /// <summary>
        ///     获取访问类型
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected String GetHttpMethod(HttpRequestBase request)
        {
            return String.Format("{0}", request.HttpMethod);
        }


        /// <summary>
        ///     格式化用户访问信息
        /// </summary>
        /// <returns></returns>
        protected String FormatUserVisitMsg(HttpRequestBase request)
        {
            return String.Format("IP:<{0}>,Url:<{1}>,IsAjax:<{2}>,HttpMethod:<{3}>,FormString:<{4}>",
                GetIp(request),
                GetVisitUrl(request),
                GetIsAjax(request),
                GetHttpMethod(request),
                GetPostParams(request));
        }

        /// <summary>
        ///     获取访问URL
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected String GetVisitUrl(HttpRequestBase request)
        {
            return String.Format("{0}", request.Url);
        }

        /// <summary>
        ///     渲染类型
        /// </summary>
        /// <returns></returns>
        protected String GetPreferredRendering(HttpRequestBase request)
        {
            return String.Format("<Type:{0}-Mime:{1}>", request.Browser.PreferredRenderingType, request.Browser.PreferredRenderingMime);
        }


        /// <summary>
        ///     获得浏览器的平台
        /// </summary>
        /// <returns></returns>
        protected String GetPlatform(HttpRequestBase request)
        {
            return request.Browser.Platform;
        }

        /// <summary>
        ///    
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected String GetUserAgent(HttpRequestBase request)
        {
            return request.UserAgent;
        }

    }
}